package com.cff.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.cff.domain.User;
import com.cff.service.user.UserService;

public class ShiroRealm extends AuthorizingRealm{
	@Autowired 
    private UserService userService;  
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
		System.out.println(token.getUsername());  	
        User user = tokenToUser(token);  
        Boolean ui = userService.login(user);  
        System.out.println("登录结果："+ui);
        if(!ui)  
            return null; // 异常处理，找不到数据  
        
        String realmName = this.getName(); 
        
        //登陆的主要信息: 可以是一个实体类的对象, 但该实体类的对象一定是根据 token 的 username 查询得到的.  
//      Object principal = ui.getUsername();  
        Object principal = authcToken.getPrincipal();  
        return new SimpleAuthenticationInfo(principal, user.getPasswd(), realmName);
	}
	
	private User tokenToUser(UsernamePasswordToken authcToken) {  
        User user = new User();  
        user.setLoginId(authcToken.getUsername());  
        user.setPasswd(String.valueOf(authcToken.getPassword()));  
        return user;  
    }  
	
}
